package com.bwhx.eruler.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.print.DocFlavor.STRING;
import javax.servlet.http.HttpServletRequest;

/**
 * 字符串工具类
 * 
 * @author Cuilitang
 *
 */
public class StringUtils {

	/**
	 * 判断输入的字符串参数是否为空
	 * 
	 * @return boolean 空则返回true,非空则flase
	 */
	public static boolean isEmpty(String input) {
		return null == input || 0 == input.trim().length() || 0 == input.replaceAll("\\s", "").length()
				|| "".equals(input);
	}

	/**
	 * 判断输入的字符串参数是否为空
	 * 
	 * @return boolean 空则返回true,非空则flase
	 */
	public static int isEmpty(String[] input) {

		for (int i = 0; i < input.length; i++) {
			if (StringUtils.isEmpty(input[i])) {
				return i;
			}
		}
		return -1;

	}

	/**
	 * 检查 email输入是否正确 正确的书写格 式为 username@domain
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkEmail(String value) {
		return value.matches("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}");
	}

	/**
	 * 检查电话输入 是否正确 正确格 式 012-87654321、0123-87654321、0123－7654321
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkTel(String value) {
		return value.matches("\\d{4}-\\d{8}|\\d{4}-\\d{7}|\\d(3)-\\d(8)");
	}

	/**
	 * 检查手机输入 是否正确
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkMobile(String value) {
		if (value.trim().length() != 11) {
			return false;
		}
		return value.matches("^1[3|4|5|7|8][0-9]\\d{8}");
	}

	public static String getRandomString(int length) {
		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(62);
			sb.append(str.charAt(number));
		}
		return sb.toString();
	}

	/*
	 * 尝试将String 转换为int
	 */
	public static int tryParseInt(String string) {
		int value = 0;
		try {
			if (string != null && !string.isEmpty()) {
				value = Integer.parseInt(string);
			}
		} catch (Exception e) {
			value = 0;
		}
		return value;
	}

	public static String GetRootPath(HttpServletRequest request) {
		String rootPath = "D:\\";
		String path = request.getContextPath();
		if (path.contains(":")) {
			rootPath = path.substring(0, path.indexOf(":")+1);
		}
		return rootPath;
	}

	public static String PrintCurrentDateTime(String msg) {
		String str = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("YYYY/MM/dd HH:mm:ss.SSS");
		str = String.format("%s\t%s", msg,sdf.format(date));
		return str;
	}
}
